//<%@ page pageEncoding="UTF-8"%>

function isArray(obj){
	try{
		var isArr = (obj.length>=0 && typeof(obj.slice)=='function');
		return isArr;
	}catch(e){
		alert('isArray error! '+e);
		return false;
	}
}

if(typeof(FormUtil)=='undefined'){
	FormUtil = {};
}

FormUtil.getFormJson=function (form){
	var json={};
	if(typeof(form)=='string'){
		form = document.getElementById(form);
	}
	if(!form)return json;
	var inputList = form.elements;
	for(var i=0;i<inputList.length;i++){
		var input=inputList[i];
		if(!input || !input.name){
			continue;
		}
		var inputType = input.type.toLowerCase();
		if(inputType=='button'){
			continue;
		}
		if((inputType=='radio'||inputType=='checkbox') && !input.checked){
			continue;
		}
		var oldVal = json[input.name];
		if(!oldVal){
			json[input.name] = input.value;
		}else{
			json[input.name] = oldVal+','+input.value;
		}
	}
	return json;
}

FormUtil.setFormJson=function(form, json){
	if(typeof(form)=='string'){
		form = document.getElementById(form);
	}
	var inputList = form.elements;
	for(var i=0;i<inputList.length;i++){
		var input=inputList[i];
		if(!input || !input.name){
			continue;
		}
		var name = input.name;
		var inputTagName = input.tagName.toLowerCase();
		var inputVal = input.value;
		var inputType = input.type.toLowerCase();
		var jsonVal = json[input.name];
		if(!jsonVal)jsonVal = "";
		
		if(inputType=='button'||inputType=='submit'||inputType=='file'){
			continue;
		}
		if((inputType=='radio'||inputType=='checkbox')){
			var inputs = FormUtil.getInputArray(name, form);
			FormUtil.setBoxValue(inputs, jsonVal);
		}else if(inputTagName=='select'){
			FormUtil.setSelectValue(input, jsonVal);
			input.preSetValue = jsonVal;
		}else{
			input.value = jsonVal;
		}

	}
	return json;
}

/* 根据json设置, 其他input忽略  */
FormUtil.setFormJson2=function(form, json){
	if(typeof(form)=='string'){
		form = document.getElementById(form);
	}
	for(var name in json){
		var jsonVal = json[name]||'';
		var input = form[name];
		if(!input || !input.name){
			continue;
		}
		
		var inputTagName = input.tagName;		
		if(inputTagName){
			if(inputTagName.toLowerCase()=='select'){
				FormUtil.setSelectValue(input, jsonVal);
				input.preSetValue = jsonVal;
			}else{
				input.value = jsonVal;
			}
		}else{
			FormUtil.setInputArray(input, jsonVal);
		}
	}
}

FormUtil.clearForm=function(form){
	if(typeof(form)=='string'){
		form = document.getElementById(form);
	}
	form.reset();
	var formInputs = form.elements;
	for(var i=0;i<formInputs.length;i++){
		var input = formInputs[i];
		if(input.type=='hidden'){
			input.value='';
		}else if(input.type=='checkbox'||input.type=='radio'){
			input.checked = false;
			input.removeAttribute('checked');
		}else if(input.type=='text' || !input.type){
			input.value='';
		}
	}
}

FormUtil.clearHideField=function(form){
	if(typeof(form)=='string'){
		form = document.getElementById(form);
	}
	var formInputs = form.elements;
	for(var i=0;i<formInputs.length;i++){
		var input = formInputs[i];
		if(input.type=='hidden'){
			input.value='';
		}
	}
}

FormUtil.fireListEvent = function(element, eventName) {
	for(var i=0; i<element.length; i++){
		this.fireEvent(element[i], eventName);
	}
}
FormUtil.fireEvent = function(element, eventName) {
	if(!element || !eventName){
		return ;
	}

	if (document.createEventObject) {
		// IE浏览器支持fireEvent方法
		var evt = document.createEventObject();
		return element.fireEvent('on' + eventName, evt);
	} else {
		// 其他标准浏览器使用dispatchEvent方法
		var evt = document.createEvent('HTMLEvents');
		// initEvent接受3个参数：
		// 事件类型，是否冒泡，是否阻止浏览器的默认行为
		evt.initEvent(eventName, false, true);
		return !element.dispatchEvent(evt);
	}
};

//IE事件顺序有问题，必须用这个..
FormUtil.exeMethod = function(obj, methodName){
	var fun = obj[methodName];
	if(fun && fun instanceof Function){
		fun.apply(obj);
		return true;
	}
	return false;
}

FormUtil.getInputArray = function(inputName, form, pname, pvalue){
	var inputs;
	if(form){
		inputs = [];
		form = typeof(form)!="string"?form:document.getElementById(form);
		var formElement = form.elements;
		for(var i=0;i<formElement.length;i++){
			if(formElement[i].name==inputName){
				inputs.push(formElement[i]);
			}
		}
	}else{
		inputs = document.getElementsByName(inputName);
	}
	
	if(pname && pvalue){
		var inputs2 = [];
		for(var i=0;i<inputs.length;i++){
			var ce = inputs[i];
			if(ce.getAttribute(pname)==pvalue||ce[pname]==pvalue){
				inputs2.push(ce);
			}
		}
		inputs = inputs2;
	}
	
	return inputs;
}

FormUtil.getInputValue = function(inputName, form, format){
	var inputs = FormUtil.getInputArray(inputName, form);
	if(format=='array'){
		var arr = [];
		for(var i=0;i<inputs.length;i++){
			var input = inputs[i];
			if(input.checked){
				arr.push(input.value);	
			}
		}
		return arr;
	}else{
		var str = '';
		for(var i=0;i<inputs.length;i++){
			var input = inputs[i];
			if(input.checked && input.value){
				if(str.length>0){
					str+=',';
				}
				str += input.value;
			}
		}
		return str;
	}
}

FormUtil.setBoxValue = function(inputArray, value){
	FormUtil.setInputArray(inputArray, value);
}

FormUtil.setInputArray = function(inputArray, value){
	if(!inputArray||!(inputArray.length>0)){
		return;
	}
	var isArr = isArray(value);
	var isStr = typeof(value)=="string";
	if(!isArr && !isStr){
		throw "类型错误";
	}
	
	var valArray = isArr?value:value.split(",");
	var changedInputArray = [];
	for(var i=0;i<inputArray.length;i++){
		var input = inputArray[i];
		var inputTagName = input.tagName.toLowerCase();
		var inputType = input.type.toLowerCase();
		var changed = false;
		if((inputType=='radio'||inputType=='checkbox')){
			for(var j=0; j<valArray.length; j++){
				if(valArray[j]==input.value){
					changed = !input.checked;
					input.checked = true;
					break;
				}
			}
		}else{
			if(input.value != valArray[i]){
				changed = true;
				input.value = valArray[i];//!
			}
		}
		if(changed){
			changedInputArray.push(input);
		}
	}
	return changedInputArray;
} 

FormUtil.setSelectValue = function(sel, val){
	var oldValue = sel.value;
	if(val == oldValue){
		return false;//if changed
	}
	for(var j=0;j<sel.length;j++){
		if(sel.options[j].value==val){
			sel.options[j].selected=true;
			break;
		}
	}
	return true;
}

FormUtil.bindSelectOptions = function(selObj, entityArray, valueProperty, textProperty, selectedValue, filterProperty, filterValue){
	if(!selObj)return;
	selObj.options.length = 1;
	for(var i=0;i<entityArray.length;i++){
		var entity = entityArray[i];
		if(filterProperty && entity[filterProperty]!=filterValue){
			continue;
		}
		var opt = new Option(entity[textProperty],entity[valueProperty]);
		selObj.options.add(opt);
	}
	if(selectedValue){
		this.setSelectValue(selObj, selectedValue);
	}
}

FormUtil.getUrlParams = function(json){
	var params = '';
	for(var name in json){
		params += name+'=';
		params += encodeURIComponent(json[name]);
		params += "&";
	}
	return params;
}

FormUtil.setSelectOptions = function(selObj, labelArray, valArray){
	if(!selObj)return;
	for(var i=0;i<valArray.length;i++){
		var text = labelArray[i];
		var val = text;
		if(valArray && valArray.length>i){
			val = valArray[i];
		}
		var opt = new Option(text, val);
		selObj.options.add(opt);
	}

}

/* 排序 */
FormUtil.sortSelect = function(obj, fromIndex){
	var fromIndex = fromIndex||0;
	var selObj = typeof(obj)!="string" ? obj:document.getElementById(obj);
	var so = selObj.options;
	var oa = [];
	for(var i=fromIndex; i<so.length; i++){
		oa.push(so[i]);
	}
	BeanUtil.sortBeans(oa, 'text', true);
	
	selObj.options.length = fromIndex;
	for(var i=0; i<oa.length; i++){
		selObj.options.add(oa[i]);
	}	
}

/* 检查select是否包含指定值 */
/* [select] [,value] */
FormUtil.checkSelectValue = function(sel, v){
	var opts = sel.options;
	for(i=0;i<opts.length;i++){
		if (opts[i].value==v)
			return i;
	}
	return -1;
}

/* 检查select是否包含指定文本 */
/* [select] [,text] */
FormUtil.checkSelectText = function(sel, text){
	var opts = sel.options;
	for(i=0;i<opts.length;i++){
		if (opts[i].text==text)
			return i;
	}
	return -1;
}

//选中指定值的选项
FormUtil.selectByValue = function(sel, v){
	var opts = sel.options;
	for(i=0;i<opts.length;i++){
		if (opts[i].value==v){
			sel.selectedIndex=i;
			return i;
		}
	}
	return -1;
}

FormUtil.setAllCheckBox = function(checkboxList, checked){
	if(typeof(checkboxList)=='string'){
		checkboxList = document.getElementsByName(checkboxList);
	}
	for(var i=0;i<checkboxList.length;i++){
		checkboxList[i].checked = (checked==true);
	}
}

//关联事件(全选)
FormUtil.associateCheckBox = function(checkboxAll, checkbox){
	checkboxAll = document.getElementById(checkboxAll);
	checkboxList = document.getElementsByName(checkbox);
	checkboxAll.onclick = function(){
		FormUtil.setAllCheckBox(checkboxList, this.checked);
	};
	function onCheckBoxClick(){
		var v = FormUtil.getInputValue(checkbox);
		checkboxAll.checked = !(!v);
	}
	for(var i=0;i<checkboxList.length;i++){
		EventUtil.addEvent(checkboxList[i], 'click', onCheckBoxClick);
	}
}

///////////////////////////////业务相关///////////////////////////////////////////

//加载下拉框选项，currentId是当前选择框的id，其之座位请求参数
function changeListOptions(currentId, childInput, childObjId, childObjLable, url, callback){
	var setChildSelect=function(childSelect, childDataList){
		childSelect.options.length = 1;
		var filterProperty = null;
		var filterValue = null;
		if(childDataList.length>0 && childDataList[0].available){
			filterProperty = 'available';
			filterValue = 'Y';
		}
		FormUtil.setSelectOptions(childSelect, childDataList, childObjId, childObjLable, childSelect.preSetValue, filterProperty, filterValue);
		if(callback)callback();
	}
	
	var currentObj = $(currentId);
	var currentValue = currentObj.value;
	var childSelect = currentObj.form[childInput];
	if(!currentValue){
		setChildSelect(childSelect, []);
		return;
	}
	//currentObj.preSetValue = currentValue;
	
	var params = {};
	params[currentId]=currentValue;
	ajaxRequest(url, params, function(result){
		var childDataList = result.retval;
		setChildSelect(childSelect, childDataList);
	})
}

function ajaxSubmit(url, formId, successFun){
	var values = FormUtil.getFormJson(formId);
	ajaxRequest(url, values, function(result){
		if(successFun){
			successFun(result);
		}else{
			location.reload();
		}
	},'post',false, true)
}

var _____;

//API统一返回对象
function _getJsonFromResponse(resp){
	var statusCode = resp.status?resp.status:null;
	if(typeof(resp)=='string'){
		statusCode = 200;
	}
	var text = typeof(resp)=='string'?resp:resp.responseText;
	var jsonObj=null;
	if(text){
	  	try{
	  		eval("jsonObj=" + text);
	  	}catch(e){
	  		jsonObj={"success":false, "msg": "网络请求错误!","status":statusCode};
	  		return jsonObj;
	  	}
	}
	if(jsonObj){
	    jsonObj.success = (jsonObj.code=="0000");
	    jsonObj.msg = jsonObj.error;
	    jsonObj.retval = jsonObj.data;
	    jsonObj.status = 200;
	}else{// onFailure
		jsonObj={"success":false, "msg": "网络请求错误！","status":statusCode};
	}
	return jsonObj;
}

